package common

import (
	"fmt"
	"github.com/gorilla/mux"
	"github.com/sirupsen/logrus"
	"io"
	"net/http"
)

func RegisterHttpFun(mux1 *mux.Router, path string, f func(http.ResponseWriter,
	*http.Request), Log *logrus.Logger) {
	Log.Info("path=", path)
	mux1.HandleFunc("/accountinfo/gamelogin", f).Methods("GET")
}

func BuildHttpListener(port int, mux1 *mux.Router, Log *logrus.Logger) {
	Log.Infof("port=%d", port)
	err := http.ListenAndServe(fmt.Sprintf(":%d", port), mux1)
	if nil != err {
		Log.Error("error=", err.Error())
	}
}

func GetRequestValue(key string, r *http.Request) string {
	value, ok := r.Form[key]
	if ok {
		if 0 < len(value) {
			return value[0]
		}
	}
	return ""
}

func GetErrorMsgJson(s string) string {
	return fmt.Sprintf("errmsg\":\"%s", s)
}

func LogAndResponse(w io.Writer, err error, Log *logrus.Logger, s string) {
	Log.Error(s, err.Error())
	fmt.Fprintf(w, GetErrorMsgJson(s))
}
